package com.mengya.locks;

import java.util.concurrent.TimeUnit;

/**
 * @ClassName DeadLockDemo
 * @Description 死锁
 * @Author xiongwei.wu
 * @Date 2023/1/9 9:48
 **/
public class DeadLockDemo {
    static Object lockA = new Object();
    static Object lockB = new Object();

    public static void main(String[] args) {
        new Thread(() -> {
            synchronized (lockA) {
                System.out.println(Thread.currentThread().getName() + "\t" + "自己持有A锁，期待获得B锁");
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException exception) {
                    exception.printStackTrace();
                }
                synchronized (lockB) {
                    System.out.println(Thread.currentThread().getName() + "\t" + "获得B锁成功");
                }
            }
        }, "t1").start();

        new Thread(() -> {
            synchronized (lockB) {
                System.out.println(Thread.currentThread().getName() + "\t" + "自己持有B锁，期待获得A锁");
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException exception) {
                    exception.printStackTrace();
                }
                synchronized (lockA) {
                    System.out.println(Thread.currentThread().getName() + "\t" + "获得A锁成功");
                }
            }
        }, "t2").start();
    }
}
